<template>
  <!-- 角色判断：护理组长显示审批页面，护理员显示结果页面 -->
  <div v-if="isNurseLeader" class="approval-page">
    <div class="content-wrapper">
      <div class="left-content">
        <!-- 基本信息区域 -->
        <el-card class="basic-info-card">
          <h3>基本信息</h3>
          <ul class="info-list">
            <li>
              <span class="label">单据编号</span
              ><span class="value">{{form.businessId || "-"}}</span>
            </li>
            <li>
              <span class="label">老人姓名</span
              ><span class="value">{{ form.elderlyName || "-" }}</span>
            </li>
            <li>
              <span class="label">老人身份证号</span
              ><span class="value">{{ form.idCard || "-" }}</span>
            </li>
            <li>
              <span class="label">联系方式</span
              ><span class="value">{{ form.phone || "-" }}</span>
            </li>
            <li>
              <span class="label">护理等级</span
              ><span class="value">{{ form.levelName || "-" }}</span>
            </li>
            <li>
              <span class="label">入住床位</span
              ><span class="value">{{ form.bed || "-" }}</span>
            </li>
            <li>
              <span class="label">护理员</span
              ><span class="value">{{ form.caregiverName?.join(", ") || "-" }}</span>
            </li>
          </ul>
        </el-card>

        <!-- 申请信息区域 -->
        <el-card class="apply-info-card">
          <h3>申请信息</h3>
          <ul class="info-list">
            <li>
              <span class="label">陪同人</span
              ><span class="value">{{
                formatCompanionType(form.companionType) || "-"
              }}</span>
            </li>
            <li>
              <span class="label">陪同人姓名</span
              ><span class="value">{{ form.companionName || "-" }}</span>
            </li>
            <li>
              <span class="label">陪同人联系方式</span
              ><span class="value">{{ form.companionPhone || "-" }}</span>
            </li>
            <li>
              <span class="label">请假周期</span
              ><span class="value">{{
                formatDateRange(form.leavePeriod) || "-"
              }}</span>
            </li>
            <li>
              <span class="label">请假天数</span
              ><span class="value">{{ form.expectedLeaveDays || "-" }}</span>
            </li>
            <li>
              <span class="label">请假原因</span
              ><span class="value">{{ form.leaveReason || "-" }}</span>
            </li>
            <li>
              <span class="label">申请人</span><span class="value">顾廷烨</span>
            </li>
            <li>
              <span class="label">申请时间</span
              ><span class="value">2048-10-05 15:00:00</span>
            </li>
          </ul>
        </el-card>
      </div>

      <div class="right-content">
        <!-- 审批结果区域 -->
        <el-card class="approval-result-card">
          <h3>审批结果</h3>
          <el-form
            :model="approvalForm"
            ref="approvalFormRef"
            label-width="120px"
          >
            <el-form-item
              label="审批结果"
              prop="auditStatus"
              :rules="[
                {
                  required: true,
                  message: '请选择审批结果',
                  trigger: 'change',
                },
              ]"
            >
              <el-radio-group v-model="approvalForm.auditStatus">
                <el-radio label="approvalPass">审批通过</el-radio>
                <el-radio label="approvalReject">审批拒绝</el-radio>
                <el-radio label="return">驳回</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="审批意见"
              prop="opinion"
              :rules="[
                { required: true, message: '请输入审批意见', trigger: 'blur' },
              ]"
            >
              <el-input
                v-model="approvalForm.opinion"
                type="textarea"
                placeholder="请输入"
                maxlength="200"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 操作记录区域 -->
        <el-card class="operation-record-card">
          <h3>操作记录</h3>
          <ul class="record-list">
            <li>
              <div class="record-item">
                <div class="record-icon"></div>
                <div class="record-content">
                  <p>发起申请-申请请假</p>
                  <p>顾廷烨 (已发起)</p>
                </div>
                <div class="record-time">2048-10-15 09:00:00</div>
              </div>
            </li>
            <li>
              <div class="record-item">
                <div class="record-icon"></div>
                <div class="record-content">
                  <p>({{ userStore.name }}) 审批-申请审批</p>
                  <p>{{ userStore.nickName || "当前用户" }} (审批中)</p>
                </div>
              </div>
            </li>
          </ul>
        </el-card>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-buttons">
      <el-button @click="handleBack" size="default">返回</el-button>
      <el-button
        type="primary"
        @click="handleSubmit"
        size="default"
        :loading="submitLoading"
        >提交</el-button
      >
    </div>
  </div>

  <!-- 护理员显示审批结果页面 -->
  <div v-else class="approval-result-page">
    <h2>审批结果</h2>
    <div class="approval-status">
      <div class="status-icon">!</div>
      <p class="status-text">审批中</p>
      <p class="status-desc">
        稍等，请假申请单正在审批中，若该申请单长时间未处理，请联系（hulizuzhang）！
      </p>
    </div>
    <div class="operation-record">
      <h4>操作记录</h4>
      <ul class="record-list">
        <li class="record-item">
          <div class="record-info">
            <p>发起申请-申请请假</p>
            <p>{{ userStore.nickName || "当前用户" }}（已发起）</p>
          </div>
          <p class="record-time">2048-10-15 09:00:00</p>
        </li>
        <li class="record-item">
          <div class="record-info">
            <p>(hulizuzhang) 审批-申请审批</p>
            <p>护理组组长 (审批中)</p>
          </div>
        </li>
      </ul>
    </div>
    <el-button @click="$emit('go-back')" size="default" class="aa"
      >返回</el-button
    >
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { addAccraditationrecord } from "@/api/accraditationrecord/accraditationrecord";
import { getTasks } from "@/api/system/tasks";
import useUserStore from "@/store/modules/user";
import { updateLeavemanage } from "@/api/leave/leavemanage";
import { getLeavemanage } from "@/api/leave/leavemanage";
import { getElderly } from "@/api/system/elderly";

// 初始化变量
const emit = defineEmits(["submit-success", "back-to-list", "go-back"]);
const router = useRouter();
const userStore = useUserStore();
const form = ref({});
const submitLoading = ref(false);
const approvalForm = ref({ auditStatus: "", opinion: "" });
const approvalFormRef = ref(null);
const id = ref(0); // 补充id初始化，避免未定义
const isShow = ref(false);

// 核心：判断当前用户是否为护理组长（根据角色标识，需和后端返回的角色值匹配）
// 假设后端返回的角色中，护理组长标识为"nurse_leader"，护理员为"nurse"
const isNurseLeader = ref(false);

// 接收父组件参数
const props = defineProps({
  prevForm: {
    type: Object,
    default: () => ({}),
  },
  leaveId:{
    type: String,
    default: () => "",
  }
});

// 监听props变化，更新表单数据
// watch(
//   () => props.prevForm,
//   (newVal) => {
//     if (newVal && Object.keys(newVal).length > 0) {
//       form.value = { ...newVal };
//       id.value = form.value.id || 0; // 从表单数据中获取id
//       console.log("步骤二接收到数据:", form.value);

//       if (id.value !== 0) {
//         getTasks(id.value).then((res) => {
//           form.value = res.data;
//           console.log("步骤二接收到数据:", form.value);
//           // 判断当前用户是否为审批人
//           if (form.value.approverId === userStore.id) {
//             isShow.value = true;
//           } else {
//             isShow.value = false;
//           }
//         });
//       }
//     }
//   },
//   { immediate: true }
// );


// 新增：根据leaveId加载申请信息和老人信息
const loadLeaveAndElderlyData = async () => {
  // 1. 先判断是否获取到leaveId
  if (!props.leaveId) {
    ElMessage.warning("未获取到请假记录ID");
    return;
  }

  try {
    // 2. 第一步：查询leave_request表（申请信息）
    const leaveRes = await getLeavemanage(props.leaveId); // 假设getLeavemanage通过ID查请假记录
    const leaveRequest = leaveRes.data; // 请假申请数据
    console.log("查询到的请假申请信息：", leaveRequest);

    // 3. 第二步：从leave_request中提取elderlyId，查询老人信息
    const elderlyId = leaveRequest.elderlyId; // 假设leave_request中老人外键字段为elderlyId
    if (!elderlyId) {
      ElMessage.warning("请假记录未关联老人");
      return;
    }

    const elderlyRes = await getElderly(elderlyId); // 假设getElderly通过ID查老人信息
    const elderly = elderlyRes.data; // 老人基本数据
    console.log("查询到的老人信息：", elderly);

    // 4. 整合数据到form，分别映射【基本信息】和【申请信息】
    form.value = {
      // —— 基本信息（来自elderly表）——
      elderlyName: elderly.name || "-", // 老人姓名
      idCard: elderly.idCard || "-", // 身份证号
      phone: elderly.contact || "-", // 联系方式（假设elderly表中字段为contact）
      levelName: elderly.levelName || "-", // 护理等级
      bed: elderly.bedNo || "-", // 入住床位（假设elderly表中字段为bedNo）
      caregiverName: elderly.caregiverNameStr 
    ? elderly.caregiverNameStr.split(',').map(item => item.trim()) // 分割并去除空格
    : [], 
      businessId: leaveRequest.businessId || "-", // 单据编号（通常在leave_request中）

      // —— 申请信息（来自leave_request表）——
      companionType: leaveRequest.companionType || "-", // 陪同人类型
      companionName: leaveRequest.companionName || "-", // 陪同人姓名
      companionPhone: leaveRequest.companionPhone || "-", // 陪同人联系方式
      leavePeriod: [leaveRequest.leaveStartTime, leaveRequest.expectedEndTime] || [], // 请假周期（数组格式）
      expectedLeaveDays: leaveRequest.expectedLeaveDays || "-", // 请假天数
      leaveReason: leaveRequest.leaveReason || "-", // 请假理由
      
      // 保存关键ID，用于后续审批提交
      id: props.leaveId, // 请假记录ID（后续更新状态用）
      elderlyId: elderlyId // 老人ID（备用）
    };
  } catch (error) {
    console.error("加载数据失败：", error);
    ElMessage.error("加载请假信息和老人信息失败，请重试");
  }
};


// 获取当前用户信息并判断角色
const getCurrentUserInfo = () => {
    isNurseLeader.value = userStore.roles.includes("zuzhang");
    console.log("当前用户角色:", userStore.roles);
    console.log("是否为护理组长:", isNurseLeader.value);
};

// 格式化陪同人类型显示
const formatCompanionType = (type) => {
  const typeMap = {
    家属: "家属",
    护理人员: "护理人员",
    其他: "其他",
    无: "无",
  };
  return typeMap[type] || type;
};

// 格式化日期范围显示
const formatDateRange = (range) => {
  if (!range || range.length < 2) return "-";
  const startDate = range[0] ? range[0].split(" ")[0] : "";
  const endDate = range[1] ? range[1].split(" ")[0] : "";
  return `${startDate} 至 ${endDate}`;
};

// 映射审批结果到审批状态
const mapApprovalResultToStatus = (result) => {
  const statusMap = {
    approvalPass: "通过",
    approvalReject: "拒绝",
    return: "驳回",
  };
  return statusMap[result] || "待审批";
};

// 表单验证
const validateApprovalForm = async () => {
  if (!approvalFormRef.value) return false;
  try {
    await approvalFormRef.value.validate();
    return true;
  } catch (error) {
    return false;
  }
};

// 处理返回
const handleBack = () => {
  emit("back-to-list");
};

// 处理提交
const handleSubmit = async () => {
  const isValid = await validateApprovalForm();
  if (!isValid) {
    ElMessage.warning("请完善审批信息");
    return;
  }
  const date = new Date();

// 获取年月日（ISO格式的日期部分）
const datePart = date.toISOString().split("T")[0]; // 如 "2025-10-26"

// 获取时分秒（ISO格式的时间部分，取前8位）
const timePart = date.toISOString().split("T")[1].slice(0, 8); // 如 "14:30:45"

  submitLoading.value = true;
  try {
    const approvalRecordData = {
      leaveRequestId: form.value.id, // 用实际表单id替换固定值
      approverId: userStore.id,
      approverName: userStore.nickName,
      approverNameRole: userStore.roles[0] || "",
      auditStatus: mapApprovalResultToStatus(approvalForm.value.auditStatus),
      opinion: approvalForm.value.opinion,
      type: "请假",
      nextStep: "请假结果",
      approvalTime: new Date().toISOString().split("T")[0],
      currentStep: "请假审批",
      handleType: "已审批",
      bussniessId: form.value.id,
      leaveContentId:form.value.id,
      finishTime: `${datePart} ${timePart}`,
    };

    console.log("提交审批记录数据:", approvalRecordData);
    await addAccraditationrecord(approvalRecordData);

    // 审批通过时更新请假状态
    if (approvalForm.value.auditStatus === "approvalPass" && form.value.id) {
      await updateLeavemanage({
        id: form.value.id,
        leaveStatus: "已批准",
      });
      console.log("请假状态更新为已批准");
    }

    const approvalInfo = {
      basicInfo: { ...form.value },
      approvalInfo: { ...approvalForm.value },
      submitData: form.value.submitData,
      approvalRecordData: approvalRecordData,
    };

    if (approvalForm.value.auditStatus === "approvalPass") {
      ElMessage.success("审批通过，审批记录已保存");
      emit("submit-success", approvalInfo);
    } else {
      ElMessage.success("审批不通过，审批记录已保存，返回申请页面");
      emit("back-to-list");
    }
  } catch (error) {
    console.error("提交审批记录失败:", error);
    ElMessage.error("提交审批记录失败，请重试");
  } finally {
    submitLoading.value = false;
  }
};

// 组件挂载时执行
onMounted(() => {
  console.log("请假审批组件已挂载", form.value);
  getCurrentUserInfo(); // 挂载时判断用户角色
  console.log("当前登录用户信息：", {
    id: userStore.id,
    name: userStore.name,
    nickName: userStore.nickName,
    roles: userStore.roles,
  });
  console.log("当前请假单ID:", props.leaveId);

  loadLeaveAndElderlyData();
  
});
</script>

<style scoped>
/* 原有样式不变，仅保留关键样式 */
.approval-page {
  padding: 20px;
}
.content-wrapper {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}
.left-content {
  flex: 2;
}
.right-content {
  flex: 1;
}
.basic-info-card,
.apply-info-card,
.approval-result-card,
.operation-record-card {
  margin-bottom: 20px;
}
.operation-record-card {
  height: 440px;
}
.info-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.info-list li {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}
.label {
  width: 120px;
  text-align: right;
  margin-right: 16px;
  color: #666;
  font-size: 14px;
}
.value {
  flex: 1;
  font-size: 14px;
  color: #333;
}
.record-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.record-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  font-size: 14px;
}
.record-icon {
  margin-right: 10px;
  margin-top: 2px;
}
.record-content {
  flex: 1;
  color: #333;
}
.record-content p {
  margin: 4px 0;
}
.record-time {
  width: 150px;
  text-align: right;
  color: #999;
}
.bottom-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

/* 护理员结果页面样式 */
.approval-result-page {
  padding: 20px;
}
.aa {
  margin-left: 600px;
}
.approval-status {
  text-align: center;
  margin-bottom: 30px;
}
.status-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border: 2px solid #ccc;
  border-radius: 50%;
  font-size: 24px;
  margin-bottom: 15px;
}
.status-text {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}
.status-desc {
  color: #666;
}
.operation-record {
  margin-bottom: 30px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 6px;
  height: 250px;
  width: 600px;
  margin-left: 300px;
}
h4 {
  margin-bottom: 15px;
}
.record-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}
.record-info p {
  margin: 5px 0;
}
.record-time {
  color: #999;
}
</style>
